import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Switch, Image, ScrollView, Text } from '@tarojs/components'
import classnames from 'classnames'
import { connect } from 'react-redux'
import { isArray } from '@/utils'
import navigationTo from '@/utils/command'
import CarInfo from '@/components/CarInfo'
import Iconfont from '@/components/Iconfont'
import EmptyView from '@/components/EmptyView'
import { getPlatformGoods, getProperty } from '@/api/goods/list'
import { getDefaultAreaInfo } from '@/api'
import { reportCmPV } from '@/utils/cloudMonitorHelper'
import monitor from '@/utils/alipayLogger'
import './index.scss'

interface IGoods {
  command: ICommand
  goodsName: string
  id: number
  originalPrice: string
  salePrice: string
  sellPointProperty: {
    propertyItemId: number
    value: string
    name: string
  }[]
  stock: number
  stockTips: string
  thumbnail: string
  promotion: any
}
interface Sort {
  id: string
  name: string
  isSelect?: boolean
}
interface State {
  selectArea: object,
  synthesize: Sort[]
  popVisible: boolean
  filterPopVisible: boolean
  list: IGoods[] | null
  propertyConfig: {
    goodsProperty: {
      checkType: number
      propertyId: number
      propertyName: string
      propertyValues: {
        id: number
        name: string
      }[]
    }[]
    isNeedMatchCar: number | boolean
    matchProperty: {
      value: string
      label: string
    }[]
    sort: Sort[]
  }
  after: {
    afterId: number
    afterTime: number
  } | {}
  isload: boolean
  matchCar: boolean
}

@connect<any>(({ car }) => ({
  car: car.carInfo.currentCar
}))
export default class Index extends Component<any, State> {
  $instance = getCurrentInstance();

  constructor (props) {
    super(props)
    this.state = {
      selectArea: {},
      propertyConfig: {},
      list: null,
      after: {},
      popVisible: false,
      filterPopVisible: false,
      synthesize: [],
      isload: false,
      matchCar: false
    }
  }

  UNSAFE_componentWillMount() { }
  onLoad(query) {
    // 打蜡和镀晶
    const { id, goodsPropertyItemIds } = this.$instance.router.params
    console.log('goodsPropertyItemIds', goodsPropertyItemIds)
    if (process.env.TARO_ENV === 'alipay' && [1, 2, 5].includes(Number(id))) {
      reportCmPV({ title: '违章查办', query })
    }

  }
  async componentDidMount() {
    const { id, cityCode } = this.$instance.router.params
    const { car } = this.props
    // 打蜡和镀晶
    if (process.env.TARO_ENV === 'alipay') {
      if (Number(id) == 1) {
        monitor.api({ api: '洗车', success: true, c1: 'taSR_CSH', time: 0 })
      } else if (Number(id) == 2) {
        monitor.api({ api: '打蜡', success: true, c1: 'taSR_CSH', time: 0 })
      } else if (Number(id) == 5) {
        monitor.api({ api: '镀晶', success: true, c1: 'taSR_CSH', time: 0 })
      }

    }
    let params: any = { frontServiceId: id }
    if (car) {
      params.carLicense = car.carLicense
    }
    let city = {}
    try {
      if (cityCode) {
        let data = await getDefaultAreaInfo({
          adCode: cityCode
        })
        let { areaCode } = data?.data.data
        city = {
          areaCode,
          cityCode
        }
        this.setState({
          selectArea: city
        })
      }
    } catch {
      //
    }
    getProperty(params).then(res => {
      const { car } = this.props
      const propertyConfig = res.data.data
      const synthesize = propertyConfig.sort.map(v => {
        v.isSelect = false
        return v
      })
      const goodsProperty = this.initProperty(propertyConfig)
      this.setState({
        matchCar: propertyConfig.isNeedMatchCar,
        synthesize,
        propertyConfig: {
          ...propertyConfig,
          goodsProperty,
          isNeedMatchCar: propertyConfig.isNeedMatchCar === '0' ? false : car ? true : false, //当前页面直接生成链接推广，因车辆信息跟商品列表同时调用导致开启失效，所以需要先判断是否有车辆
        }
      }, () => this.getPlatformGoods('reset'))
    })
  }

  // UNSAFE_componentWillReceiveProps(nextProps) {
  //   const { id } = this.$instance.router.params
  //   const { car } = nextProps
  //   let params: any = { frontServiceId: id }
  //   if (car) {
  //     params.carLicense = car.carLicense
  //   }
  //   getProperty(params).then(res => {
  //     const propertyConfig = res.data.data
  //     const synthesize = propertyConfig.sort.map(v => {
  //       v.isSelect = false
  //       return v
  //     })
  //     const goodsProperty = this.initProperty(propertyConfig)
  //     this.setState({
  //       matchCar: propertyConfig.isNeedMatchCar,
  //       synthesize,
  //       propertyConfig: {
  //         ...propertyConfig,
  //         goodsProperty,
  //         isNeedMatchCar: propertyConfig.isNeedMatchCar === '0' ? false : true
  //       }
  //     }, () => this.getGoods('reset'))
  //   })
  //   console.log(nextProps)
  // }
  componentWillUnmount() {
    this.getPlatformGoods('reset')
  }
  private listLoaded = false

  // 车辆匹配开关
  private changeSwitch = () => {
    console.log('点击出发了吗---')
    if (this.listLoaded) return
    const {
      propertyConfig
    } = this.state
    const switchStatus = propertyConfig.isNeedMatchCar
    this.setState({
      propertyConfig: {
        ...propertyConfig,
        isNeedMatchCar: !switchStatus
      }
    }, () => {
      this.goodsProperty = [-1]
      this.getPlatformGoods('reset')
    })
  }

  // 下拉加载
  scrollToLower(e) {
    // console.log(e)
    this.getPlatformGoods()
  }

  routeTo(command) {
    const { car } = this.props
    if (!car && command.commandName === 'maintain') {
      Taro.navigateTo({
        url: '/pages/car/add/index'
      })
    } else {
      let { cityCode = '', storeCode = '' } = this.$instance.router.params
      if (cityCode) {
        command.query.cityCode = cityCode
      }
      if (storeCode) {
        command.query.cityCode = cityCode
      }
      navigationTo(command)
    }
  }

  // 车辆属性匹配
  switchView = () => {
    const {
      propertyConfig,
      isload,
      matchCar
    } = this.state
    const { matchProperty, isNeedMatchCar: switchStatus } = propertyConfig
    console.log('switchStatus', switchStatus)
    return (
      <View className='goods-list-switchwrap'>
        {
          matchCar ? <View className='goods-list-switch'>
            <View className='at-row'>
              <View className='at-col at-col-10'>
                <Iconfont name='icon-shezhi' size='43' color={switchStatus ? '#12b3ff' : '#999'} />
                <View className={classnames(switchStatus ? 'theme-color' : 'theme-color-3')} >
                  根据您的车型信息，智能匹配以下商品
                </View>
              </View>
              <View className='at-col at-col-2 at-col--auto'>
                <Switch color={switchStatus ? '#12b3ff' : '#999'} onChange={this.changeSwitch} disabled={isload} checked={Boolean(switchStatus)} />
              </View>
            </View>
          </View> : null
        }
        {
          switchStatus && matchProperty && matchProperty.length > 0 && (
            <View className='goods-list-rule'>
              <View className='at-row at-row__justify--center'>
                {
                  matchProperty.map((v, idx) => {
                    return (
                      <View key={v.value} className='self-col at-col-4'>
                        <View className='theme-color'>{v.value}</View>
                        <View className='theme-color-2'>{v.label}</View>
                      </View>
                    )
                  })
                }
              </View>
            </View>
          )
        }
      </View>
    )
  }

  // 综合弹窗
  popView = () => {
    const {
      popVisible,
      synthesize
    } = this.state

    return (popVisible &&
      <View className={classnames('goods-list-pop')} onTouchMove={(e) => e.stopPropagation()} >
        <View className='goods-list-pop-mask' onClick={() => { this.setState({ popVisible: false }) }}></View>
        <View className='goods-list-pop-item'>
          {
            synthesize.map((_type, _typeIdx) => {
              return (
                <View key={_type.id} className={classnames('goods-list-pop-li', {
                  'act': _type.isSelect
                })} onClick={() => this.checkView(_typeIdx)}
                >{_type.name}</View>
              )
            })
          }
        </View>
      </View>
    )
  }

  // 筛选抽屉弹窗
  filterPop = () => {
    const {
      filterPopVisible,
      propertyConfig
    } = this.state
    const { goodsProperty } = propertyConfig
    return goodsProperty && (
      <View className={classnames('filter-popview', {
        show: filterPopVisible
      })}
      >
        <View onClick={() => this.setState({ filterPopVisible: false })} className='filter-popview-mask'></View>
        <View className='filter-popview-content right'>
          <View className='filter-popview-content-title'>筛选</View>
          <View className='filter-popview-wrap'>
            {
              goodsProperty.map((v, propertyIdx) => {
                return (
                  <View key={v.propertyId} className='filter-popview-content-property'>
                    <View className='title'>{v.propertyName}</View>
                    <View className='filter-popview-item'>
                      {
                        v.propertyValues.map(property => {
                          return <View onClick={() => this.filterProperty(propertyIdx, property.id)} key={property.id} className={classnames('filter-popview-li', property.isSelect && 'act')}>{property.itemValue}</View>
                        })
                      }
                    </View>
                  </View>
                )
              })
            }
          </View>
          <View className='btn-group'>
            <View className='btn' onClick={() => this.resetProperty()}>重置</View>
            <View className='btn' onClick={() => this.confirm()}>确定</View>
          </View>
        </View>
      </View>
    )
  }


  // 筛选菜单
  filterMenu = () => {
    const {
      popVisible,
      synthesize,
      propertyConfig
    } = this.state
    const synthesizeStatus = synthesize.some(v => v.isSelect)
    const currProperty = synthesize.find(v => v.isSelect)
    const { goodsProperty } = propertyConfig
    return (
      <View className={classnames('goods-list-query', goodsProperty.length > 0 ? 'col-2' : 'col-1')}>
        <View className={classnames('goods-list-query-li', {
          'act': synthesizeStatus
        })} onClick={() => {
          this.setState({ popVisible: !popVisible })
        }}
        >
          <View className='goods-list-query-name'>{currProperty ? currProperty.name : '综合'}</View>
          <Iconfont size='20' color={synthesizeStatus ? '#12B3FF' : '#333'} name='icon-shaixuanxialajiantou'></Iconfont>
        </View>
        {
          goodsProperty.length ?
            <View onClick={() => this.setState({ filterPopVisible: true })} className='goods-list-query-li'>
              <View className='goods-list-query-name'>筛选</View>
              <Iconfont size='20' color='#333' name='icon-shaixuanxialajiantou'></Iconfont>
            </View> : null
        }
      </View>
    )
  }

  // 商品列表
  goodsList = () => {
    const { list } = this.state
    return list && list.length > 0 ? (
      <View className='goods-list-item'>
        {
          list.map((v, idx) => {
            return (
              <View key={v.id} onClick={() => this.routeTo(v.command)} className='goods-list-item-li'>
                <View className="img-block">
                  <Image lazyLoad src={v.thumbnail} className='goods-list-item-li__img goods-list-item-position' />
                  {
                    v.promotion && v.promotion.listImageUrl !== null ? <Image lazyLoad src={v.promotion.listImageUrl} className='goods-list-item-li__img goods-list-item-position' /> : ''
                  }
                </View>
                <View className='goods-list-item-li__content'>
                  <View className='goods-list-item-li__content-title theme-color-2'>{v.goodsName}</View>
                  {
                    v.sellPointProperty.length > 0 ? (
                      <View className='goods-list-item-li__content-rule'>
                        <View className='at-row self-row'>
                          {
                            v.sellPointProperty && v.sellPointProperty.map(sellPoint => {
                              return (
                                <View key={sellPoint.propertyItemId} className='self-col'>
                                  <View className='theme-color-2'>{sellPoint.value}</View>
                                  <View className='theme-color-3'>{sellPoint.name}</View>
                                </View>
                              )
                            })
                          }
                        </View>
                      </View>
                    ) : null
                  }
                  <View className='goods-list-item-li__content-price'>
                    {
                      v.warranty && <View className='goods-list-item-li__content-price-warranty'>{v.warranty}</View>
                    }
                    <View className='price-1'>￥{Number(v.salePrice)}
                      {
                        Number(v.salePriceRange.maxPrice) !== Number(v.salePriceRange.minPrice) ? <Text className='price-area'>起</Text> : null
                      }
                    </View>
                    {/* <View className='price-2'>￥{v.originalPrice}</View> */}
                  </View>
                </View>
              </View>
            )
          })
        }
      </View>
    ) : list && <EmptyView title='没有合适的推荐商品~' />
  }

  // 综合勾选状态
  private checkView(idx: number) {
    const {
      synthesize
    } = this.state
    this.setState({
      popVisible: false,
      synthesize: synthesize.map((v, i) => {
        if (i === idx) {
          v.isSelect = !v.isSelect
        } else {
          v.isSelect = false
        }
        return v
      })
    }, () => this.getPlatformGoods('reset'))
  }

  // 初始化筛选属性
  private initProperty(prperty) {
    const { goodsPropertyItemIds } = this.$instance.router.params
    let defaultGoodsPropertyItemIds = []
    if (goodsPropertyItemIds) {
      defaultGoodsPropertyItemIds = JSON.parse(goodsPropertyItemIds)
    }
    const propertyConfig = prperty || this.state.propertyConfig
    if (propertyConfig.goodsProperty) {
      propertyConfig.goodsProperty.map(v => {
        if (v.propertyValues.length > 0) {
          v.propertyValues.map(property => {
            if (defaultGoodsPropertyItemIds.findIndex(i => i == property.id) > -1) {
              this.isFilter = true
              property.isSelect = true
            } else {
              property.isSelect = false
            }
            return property
          })
        }
        return v
      })
    }
    return propertyConfig.goodsProperty
  }

  // 重置筛选
  private resetProperty() {
    const { propertyConfig } = this.state
    const goodsProperty = this.initProperty(propertyConfig)
    this.goodsProperty = [-1]
    this.setState({
      propertyConfig: {
        ...propertyConfig,
        goodsProperty
      },
      filterPopVisible: false
    }, () => this.getPlatformGoods('reset'))
  }

  isFilter: boolean = false
  // 确定筛选
  confirm() {
    this.isFilter = true
    this.getPlatformGoods('reset')
    this.setState({
      filterPopVisible: false
    })
  }

  // 筛选
  private filterProperty(idx: number, id: number) {
    const {
      propertyConfig
    } = this.state
    const { goodsProperty } = propertyConfig

    const property = goodsProperty[idx]
    if (property.checkType) {
      // 多选
      property.propertyValues.map(v => {
        if (v.id === id) {
          v.isSelect = !v.isSelect
        }
        return v
      })
    } else {
      // 单选
      property.propertyValues.map(v => {
        if (v.id === id) {
          v.isSelect = !v.isSelect
        } else {
          v.isSelect = false
        }
        return v
      })
    }
    this.setState({
      propertyConfig
    })
  }

  private isPageEnd: boolean = false
  private goodsProperty = [-1]
  // 获取商品列表
  getPlatformGoods(params: any = {}, type?: string) {
    if (typeof params === 'string') {
      type = params
      params = {}
    }
    if (type === 'reset') {
      this.isPageEnd = false
    }
    if (this.isPageEnd) return

    const { car } = this.props
    const { id, cityCode } = this.$instance.router.params
    let { selectArea } = this.state
    const {
      propertyConfig,
      synthesize,
      after
    } = this.state

    let newParams: any = {
      frontServiceId: id
    }
    if (car) {
      newParams.carLicense = car.carLicense
    }

    if (cityCode) {
      newParams.cityCode = selectArea.cityCode
      newParams.areaCode = selectArea.areaCode
    }


    if (propertyConfig.sort) {
      const sort = synthesize.find(v => v.isSelect)
      const goodsProperty: any = []
      for (let property of propertyConfig.goodsProperty) {
        property.propertyValues.forEach(v => {
          if (v.isSelect) {
            goodsProperty.push(v.id)
          }
        })
      }
      if (
        this.isFilter &&
        goodsProperty.length === this.goodsProperty.length &&
        goodsProperty.every(v => this.goodsProperty.some(n => n === v))
      ) {
        this.isFilter = false
        return
      }
      this.goodsProperty = goodsProperty
      newParams = {
        ...newParams,
        sortBy: sort ? sort.id : 'sortCompositeDefault',
        goodsPropertyItemIds: JSON.stringify(goodsProperty),
        isMatchCar: propertyConfig.isNeedMatchCar
      }
    } else {
      newParams = {
        ...newParams,
        isMatchCar: propertyConfig.isNeedMatchCar
      }
    }

    params = Object.assign({}, newParams, params)
    if (type !== 'reset') {
      if (isArray(after)) {
        return
      } else {
        params = {
          ...params,
          afterId: after.afterId,
          afterTime: after.afterTime
        }
      }
    }
    if (this.listLoaded) return
    this.listLoaded = true
    this.setState({
      isload: true
    })
    Taro.showLoading({ title: '正在加载' })
    getPlatformGoods({
      ...params,
      isMatchCar: params.isMatchCar ? '1' : '0'
    }).then(res => {
      const data = res.data.data
      this.isFilter = false
      if (!isArray(data)) {
        const { list } = this.state
        this.listLoaded = false
        Taro.hideLoading()
        if (data.after.afterId === 0) {
          this.isPageEnd = true
        }
        this.setState({
          isload: false,
          after: data.after,
          list: type === 'reset' ? data.goods : [...list, ...data.goods]
        }, () => Taro.pageScrollTo({ scrollTop: 0 }))
      } else {
        this.isPageEnd = true
        this.setState({
          isload: false,
          after: []
        })
      }
    }).catch(e => {
      this.setState({
        isload: false
      })
      this.listLoaded = false
      this.isFilter = false
      Taro.hideLoading()
    })
  }

  render() {
    const {
      propertyConfig,
      matchCar
    } = this.state
    const switchStatus = propertyConfig.isNeedMatchCar

    return propertyConfig.matchProperty ? (
      <ScrollView
        scrollY
        refresherThreshold={100}
        onScrollToLower={this.scrollToLower.bind(this)}
        className={classnames('goods-list', {
          'has-rule': switchStatus && propertyConfig.matchProperty.length > 0,
          'hide-rule': propertyConfig.matchProperty.length === 0 && !matchCar,
          'switch': propertyConfig.matchProperty.length === 0 && matchCar
        })}
      >
        <View className='goods-list-hd'>
          <CarInfo />
          {this.switchView()}
          {this.filterMenu()}
        </View>
        <View className='goods-list-bd'>
          {this.goodsList()}
        </View>
        {this.popView()}
        {this.filterPop()}
      </ScrollView>
    ) : null
  }
}
